package com.zhaolulu.config;

/**
 * @author 火飞鹰
 * @CSDN https://blog.csdn.net/weixin_44811903
 * @date 2025/8/14 21:49
 * @Description
 */

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class SpringfoxConfig {

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerProviders((WebMvcRequestHandlerProvider) bean);
                }
                return bean;
            }
        };
    }

    private static void customizeSpringfoxHandlerProviders(WebMvcRequestHandlerProvider bean) {
        try {
            Field field = ReflectionUtils.findField(WebMvcRequestHandlerProvider.class, "handlerMappings");
            if (field != null) {
                ReflectionUtils.makeAccessible(field);
                List<RequestMappingInfoHandlerMapping> mappings =
                        (List<RequestMappingInfoHandlerMapping>) ReflectionUtils.getField(field, bean);
                if (mappings != null) {
                    // 过滤掉可能导致问题的映射
                    List<RequestMappingInfoHandlerMapping> filteredMappings = mappings.stream()
                            .filter(mapping -> mapping.getPatternParser() == null)
                            .collect(Collectors.toList());
                    ReflectionUtils.setField(field, bean, filteredMappings);
                }
            }
        } catch (Exception e) {
            // 忽略异常
        }
    }
}
